package com.lincoln.framework.controller.sys;

import com.lincoln.framework.annotation.UnAuth;
import com.lincoln.framework.common.Constant;
import com.lincoln.framework.bean.SysLoginAdmin;
import com.lincoln.framework.bean.SysRoleRights;
import com.lincoln.framework.common.WebUtils;
import com.lincoln.framework.entity.SysAdmin;
import com.lincoln.framework.service.SysAdminService;
import com.lincoln.framework.service.SysMenuService;
import com.lincoln.framework.utils.MD5;
import com.lincoln.framework.utils.ParameterChecker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 系统端登录controller
 * 
 * @author zwm
 */
@UnAuth
@Controller
@RequestMapping("/sys")
public class LoginController extends SysBaseController {

	@Autowired
	private SysAdminService sysAdminService;
	
	@Autowired
	private SysMenuService sysMenuService;

	/**
	 * 输入×次数显示验证码
	 */
	private static final int SHOW_SAFE_CODE_ERRORTIMES = 3;

	/**
	 * 系统端验证码
	 */
	private static final String SESSION_SYS_ADMIN_SAFE_CODE = "session_sys_admin_safe_code";

	/**
	 * 系统登录错误次数
	 */
	private static final String COOKIE_SYS_ADMIN_LOGIN_ERROR_TIMES = "cookies_error_times";

	/**
	 * session中保存的异常次数
	 */
	private static final String SESSION_SYS_ADMIN_LOGIN_ERRORTIMES = "session_sys_admin_login_errortimes";

	/**
	 * 跳转登录页
	 */
	@RequestMapping("/toLogin.do")
	public String toLogin(HttpServletRequest request, HttpServletResponse response, Model model) {
		int errorTimes = this.getLoginErrorTimes(request);

		model.addAttribute("errorTimes", errorTimes);
		return "sys/login/index";
	}

	/**
	 * 登录方法
	 */
	@RequestMapping("/login.do")
	public void login(HttpServletRequest request, HttpServletResponse response) {
		int errorTimes = this.getLoginErrorTimes(request);
		String safecode = request.getParameter("safecode");
		String sessionsafecode = getSafeCodeValues();
		if (errorTimes >= SHOW_SAFE_CODE_ERRORTIMES
				&& (safecode == null || safecode.trim().equals("") || !safecode.toLowerCase().equals(
						sessionsafecode == null ? "" : sessionsafecode.toLowerCase()))) {
			this.setAttributes("focusId", "safecode");
			this.addErrorTimesAndReturnError(errorTimes, "请输入正确验证码");
			return;
		}
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		if (ParameterChecker.isNullOrEmpty(name)) {
			this.setAttributes("focusId", "name");
			this.addErrorTimesAndReturnError(errorTimes, "请输入用户名");
			return;
		}
		if (ParameterChecker.isNullOrEmpty(password)) {
			this.setAttributes("focusId", "password");
			this.addErrorTimesAndReturnError(errorTimes, "请输入密码");
			return;
		}
		SysAdmin admin = sysAdminService.getSysAdminByNameAndPassword(name.trim(), MD5.hex_md5(password));
		if (admin == null) {
			this.setAttributes("focusId", "name");
			this.addErrorTimesAndReturnError(errorTimes, "用户名或密码错误，请重新输入");
			return;
		}
		if (admin.getStatus() == SysAdmin.STATUS_DISABLE) {
			this.addErrorTimesAndReturnError(errorTimes, "账号已停用，请联系管理员");
			return;
		}

		SysLoginAdmin loginAdmin = new SysLoginAdmin(admin);
		if(loginAdmin.isSupperAdmin()) {
			SysRoleRights rights = new SysRoleRights(sysMenuService.findByParentIdAndLevel(0, 0));
			loginAdmin.setSysRoleRights(rights);
		}
		WebUtils.saveSysLoginAdmin(loginAdmin);

		admin.setLastLoginIp(WebUtils.getClientIp());
		admin.setLastLoginTime(new Date());
		sysAdminService.saveSysAdmin(admin);

		this.getRequest().getSession().removeAttribute(SESSION_SYS_ADMIN_SAFE_CODE);
		this.getRequest().getSession().removeAttribute(SESSION_SYS_ADMIN_LOGIN_ERRORTIMES);
		
		this.addSysAdminLog("管理员【" + admin.getName() + "】登录");
		this.returnSuccess();
	}

	/**
	 * 获取二维码图片
	 */
	@RequestMapping("/getSafeCode.do")
	@ResponseBody
	public void getSafeCode() {
		this.renderValidateImg(SESSION_SYS_ADMIN_SAFE_CODE);
	}

	/**
	 * 退出登录
	 * 
	 * @return String
	 */
	@RequestMapping("/logout.do")
	public String logout(HttpServletRequest request, HttpServletResponse response, Model model) {
		getRequest().getSession().removeAttribute(Constant.SESSION_SYS_ADMIN_LOGIN);
		this.getRequest().getSession().removeAttribute(SESSION_SYS_ADMIN_SAFE_CODE);

		this.toLogin(request, response, model);
		return "sys/login/index";
	}

	/**
	 * 获取登录错误次数
	 * 
	 * @param request
	 * @return int
	 */
	private int getLoginErrorTimes(HttpServletRequest request) {
		int errorTimes = 0;
		Cookie errorTimeCookie = this.getCookie(COOKIE_SYS_ADMIN_LOGIN_ERROR_TIMES);
		if (errorTimeCookie != null) {
			errorTimes = Integer.parseInt(errorTimeCookie.getValue());
		}
		Object sessionErrorTimeObj = request.getSession().getAttribute(SESSION_SYS_ADMIN_LOGIN_ERRORTIMES);
		int sessionErrorTime = sessionErrorTimeObj != null ? Integer.valueOf(sessionErrorTimeObj.toString()) : 0;
		errorTimes = errorTimes > sessionErrorTime ? errorTimes : sessionErrorTime;
		return errorTimes;
	}

	/**
	 * 获取当前dengue验证码内容
	 * 
	 * @return String
	 */
	private String getSafeCodeValues() {
		Object safeCode = this.getRequest().getSession().getAttribute(SESSION_SYS_ADMIN_SAFE_CODE);
		return safeCode != null ? safeCode.toString() : null;
	}

	private void addErrorTimesAndReturnError(int errorTimes, String msg) {
		this.setAttributes("errorTimes", errorTimes + 1);
		this.getRequest().getSession().setAttribute(SESSION_SYS_ADMIN_LOGIN_ERRORTIMES, errorTimes + 1);
		this.returnError(msg);
	}

}
